<template>
  <div>
    <section class="jarallax py-5">
      <img src="@/assets/images/banner-1.jpg" class="jarallax-img">
      <div class="hero-content py-0 py-md-5">
        <div class="container-lg d-flex flex-column d-md-block align-items-center">
          <nav class="breadcrumb">
            <a class="breadcrumb-item nav-link" href="/Organic/home">主页</a>
            <a class="breadcrumb-item nav-link" href="/Organic/checkout">页面</a>
            <span class="breadcrumb-item active" aria-current="page">结账</span>
          </nav>
          <h1>收款处</h1>
        </div>
      </div>
    </section>

    <section class="shopify-cart checkout-wrap py-5">
      <div class="container-lg">
        <div class="row g-5">
          <div class="col-md-5 col-lg-4 order-md-last">
            <h4 class="d-flex justify-content-between align-items-center mb-3">
              <span class="text-primary">你的购物车</span>
              <span class="badge bg-primary rounded-pill">{{carts.length}}</span>
            </h4>
            <ul class="list-group mb-3">
              <li class="list-group-item d-flex justify-content-between lh-sm" v-for="(cart) in carts" :key="cart.cartId">
                <div>
                  <h6 class="my-0">{{cart.product.name}}</h6>
                  <small class="text-body-secondary">￥{{cart.product.price}}*{{cart.num}}</small>
                </div>
                <span class="text-body-secondary">￥{{cart.product.price*cart.num}}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span>总计(￥)</span>
                <strong>￥<span v-text="subtotal"></span></strong>
              </li>
            </ul>
          </div>
          <div class="col-md-7 col-lg-8">
            <h4 class="mb-3">我的订单</h4>
            <el-form :model="checkoutForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="checkoutForm.name" :value="user.realName"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model="checkoutForm.phone" :value="user.phone"></el-input>
              </el-form-item>
              <el-form-item label="地址" prop="address">
                <el-input v-model="checkoutForm.address" :value="user.userAddress[0].address" @focus="handlePickUpPoint"></el-input>
              </el-form-item>
              <el-form-item prop="merchantId">
                <el-input style="display: none" v-model="checkoutForm.merchantId"></el-input>
              </el-form-item>
              <el-form-item label="自提点" prop="pickUpPoint">
                <el-input v-model="checkoutForm.pickUpPoint"></el-input>
                <el-button type="primary" @click="handlePickUpPoint">选择自提点</el-button>
                <el-dialog title="地址" :visible.sync="showAddressDialog" width="80%" >
                  <div style="height: 550px">
                    <Map ref="map" @updateLocation="updateLocation" @initAddress="initAddress"/>
                  </div>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="showAddressDialog = false">取 消</el-button>
                    <el-button type="primary" @click="setMapAddrToAddress">确 定</el-button>
                  </span>
                </el-dialog>
              </el-form-item>
              <h4 class="mb-3">付款方式</h4>
              <el-form-item label="付款方式" prop="payment">
                <el-select v-model="checkoutForm.payment" placeholder="请选择付款方式">
                  <el-option label="余额" value="P002-1"></el-option>
                  <el-option label="支付宝" value="P002-2"></el-option>
                  <el-option label="微信" value="P002-3"></el-option>
                </el-select>
              </el-form-item>
              <hr class="my-4">
              <button class="w-100 btn btn-primary btn-lg" type="button" @click="submitUpload('ruleForm')">结账</button>
            </el-form>
            <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">
              <span>是否立即付款</span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="pay(orderNumber)">确 定</el-button>
              </span>
            </el-dialog>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import Map from "@/components/OrganicBody/AMap.vue";

export default {
  name: 'CheckoutBody',
  components: {Map},
  props: {},
  data () {
    return {
      user: {},
      carts: [],
      checkoutForm: {
        name: '',
        phone: '',
        address: '',
        pickUpPoint: '',
        payment: '',
        merchantId: '',
        subtotal: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
        ],
        pickUpPoint: [
          { required: true, message: '请输入自提点', trigger: 'blur' }
        ],
        payment: [
          { required: true, message: '请选择付款方式', trigger: 'blur' }
        ],

      },
      showAddressDialog: false,
      selectedLocation: null,
      dialogVisible : false,
      orderNumber:'',
    }
  },
  computed: {
    subtotal() {
      return this.carts.reduce((sum, cart) => sum + cart.product.price * cart.num, 0);
    }
  },
  methods: {
    intUser(){
      this.user=this.$store.state.user;
      this.carts=this.$store.state.carts;
      this.intCheckout()
    },
    intCheckout(){
      this.checkoutForm.name=this.user.realName;
      this.checkoutForm.phone=this.user.phone;
      this.checkoutForm.address=this.user.userAddress[0].address+'-'+this.user.userAddress[0].detailAddress;
    },
    handlePickUpPoint(){
      this.showAddressDialog = true;
    },
    initAddress(addr){
      console.log('addr',addr)
    },
    updateLocation(Addr) {
      console.log('接收到的地址信息:', Addr);
      // eslint-disable-next-line no-empty
      if(Addr.merchantId === undefined || Addr.merchantId === '' ||Addr.merchantId === 0){
        this.$notify({
          title: '自提点选择失败！',
          message: `无效自提点！！！请重新选择。`,
          type: 'error',
          duration: 2000
        });
      }else {
        this.$notify({
          title: '自提点选择成功！',
          message: `地址: ${Addr.orgAddr}`,
          type: 'success',
          duration: 2000
        });
        this.selectedLocation = Addr;
      }

    },
    setMapAddrToAddress(){
      if (this.selectedLocation ) {
        this.checkoutForm.pickUpPoint = this.selectedLocation.orgAddr;
        this.checkoutForm.merchantId = this.selectedLocation.merchantId;
      }
      this.showAddressDialog = false;
    },
    submitUpload() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.checkoutForm.merchantId === undefined || this.checkoutForm.merchantId === '' || this.checkoutForm.merchantId === 0) {
            this.$notify({
              title: '自提点选择失败！',
              message: `无效自提点！！！请重新选择。`,
              type: 'error',
              duration: 2000
            });
            return;
          }

          this.checkoutForm.subtotal = this.subtotal;
          let formData = {
            user: this.user,
            carts: this.carts,
            checkoutForm: this.checkoutForm
          };


          this.$axios.post('http://localhost:8090/orders/exAdd', formData).then(({ data }) => {
            // eslint-disable-next-line no-empty
            if(data !== null && data !== undefined){
              this.$notify({
                title: '结账成功',
                message: '订单提交成功,正在前往支付。',
                type: 'success'
              });
              this.orderNumber = data.orderNumber;
              this.carts = [];
              this.$store.commit('setCarts', this.carts);
              this.dialogVisible = true;
            }else {
              this.$notify({
                title: '结账失败',
                message: '订单提交失败',
                type: 'warning'
              });
            }
          })
        } else {
          this.$notify({
            title: '结账失败',
            message: '请检查表单输入是否正确',
            type: 'warning'
          });
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
    pay(orderNumber){
      // eslint-disable-next-line no-empty
      if(orderNumber !== ''|| orderNumber !== null || orderNumber !== undefined){
        window.open(`http://localhost:8090/alipay/pay?orderNo=${orderNumber}`);
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
          })
          .catch(() => {});
    },
  },
  created () {
    this.intUser();
  },
}
</script>

<style scoped>

</style>
